package com.sskj.fabi.ui.activity;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.IntentUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.FabiOrderStatusEnum;
import com.sskj.fabi.bean.OrderDetailBean;
import com.sskj.fabi.presenter.OrderRecordDetailActivityPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.adapter.SpinnerTextColorAdapter;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.FabiBuySellEnum;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.TimeFormatUtil;
import com.sskj.lib.util.TipUtil;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.FABI_ORDER_RECORD_DETAIL)
public class OrderRecordDetailActivity extends BaseActivity<OrderRecordDetailActivityPresenter> {
    @BindView(R2.id.tvTitleOrder)
    TextView tvTitleOrder;
    @BindView(R2.id.tvOrderNum)
    TextView tvOrderNum;
    @BindView(R2.id.tvStatus)
    TextView tvStatus;
    @BindView(R2.id.tvTradeType)
    TextView tvTradeType;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvNum)
    TextView tvNum;
    @BindView(R2.id.tvAllMoney)
    TextView tvAllMoney;
    @BindView(R2.id.tvRemark)
    TextView tvRemark;
    @BindView(R2.id.pay_type)
    TextView payType;
    @BindView(R2.id.tvAlipayAccount)
    TextView tvAlipayAccount;
    @BindView(R2.id.ivAlipay)
    ImageView ivAlipay;
    @BindView(R2.id.llAlipay)
    LinearLayout llAlipay;
    @BindView(R2.id.tvWeChatAccount)
    TextView tvWeChatAccount;
    @BindView(R2.id.ivWechat)
    ImageView ivWechat;
    @BindView(R2.id.llWeChat)
    LinearLayout llWeChat;
    @BindView(R2.id.tvBankAccount)
    TextView tvBankAccount;
    @BindView(R2.id.tvBank)
    TextView tvBank;
    @BindView(R2.id.tvBankBranch)
    TextView tvBankBranch;
    @BindView(R2.id.llBank)
    LinearLayout llBank;
    @BindView(R2.id.tvBuyerFirst)
    TextView tvBuyerFirst;
    @BindView(R2.id.tvBuyerSecond)
    TextView tvBuyerSecond;
    @BindView(R2.id.btBuyerSure)
    Button btBuyerSure;
    @BindView(R2.id.tvBuyerCancel)
    TextView tvBuyerCancel;
    @BindView(R2.id.llBuyerWaitPay)
    LinearLayout llBuyerWaitPay;
    @BindView(R2.id.tvSellerWaitCoinFirst)
    TextView tvSellerWaitCoinFirst;
    @BindView(R2.id.tvSellerWaitCoinSecond)
    TextView tvSellerWaitCoinSecond;
    @BindView(R2.id.btSellerWaitCoinSure)
    Button btSellerWaitCoinSure;
    @BindView(R2.id.tvSellerWaitCoinCancel)
    TextView tvSellerWaitCoinCancel;
    @BindView(R2.id.llSellerWaitCoin)
    LinearLayout llSellerWaitCoin;
    @BindView(R2.id.tvSellerWaitPayFirst)
    TextView tvSellerWaitPayFirst;
    @BindView(R2.id.btSellerWaitPaySure)
    Button btSellerWaitPaySure;
    @BindView(R2.id.llSellerWaitPay)
    LinearLayout llSellerWaitPay;
    @BindView(R2.id.tvBuyerWaitCoinFirst)
    TextView tvBuyerWaitCoinFirst;
    @BindView(R2.id.tvBuyerWaitCoinSecond)
    TextView tvBuyerWaitCoinSecond;
    @BindView(R2.id.llBuyerWaitCoin)
    LinearLayout llBuyerWaitCoin;
    @BindView(R2.id.tvAppealing)
    TextView tvAppealing;
    @BindView(R2.id.llAppealing)
    LinearLayout llAppealing;
    @BindView(R2.id.tvCancel)
    TextView tvCancel;
    @BindView(R2.id.llCancel)
    LinearLayout llCancel;
    @BindView(R2.id.tvComplete)
    TextView tvComplete;
    @BindView(R2.id.llComplete)
    LinearLayout llComplete;
    @BindView(R2.id.ivCall)
    ImageView ivCall;
    @Autowired
    boolean isBuyer;
    @Autowired
    String orderNum;
    private String[] stringArray;
    private HashMap<String, String> payTipMap;
    private OrderDetailBean data;
    private Disposable timerDispo;
    private MaterialDialog payTipDialog;
    private MaterialDialog tipCancleDialog;
    private Disposable detailDispo;
    private BottomSheetDialog codeDialog;
    private SpinnerTextColorAdapter mAdapter;
    private AlertDialog tipAppealDialog;
    private Disposable payTypeDispo;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_activity_order_record_detail;
    }

    @Override
    public OrderRecordDetailActivityPresenter getPresenter() {
        return new OrderRecordDetailActivityPresenter();
    }

    @Override
    protected void initView() {
        setTitle(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity1_h));
        ARouter.getInstance().inject(this);
        stringArray = getResources().getStringArray(R.array.fabi_appeal);
        llAlipay.setVisibility(View.GONE);
        llBank.setVisibility(View.GONE);
        llWeChat.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        payTipMap = new HashMap<>();
        payTipMap.put("1", App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity2_h));
        payTipMap.put("2", App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity3_h));
        mPresenter.getOrderInfo(orderNum, true);
    }

    public void updateUI(OrderDetailBean data) {
        this.data = data;
        llAlipay.setVisibility(View.GONE);
        llBank.setVisibility(View.GONE);
        llWeChat.setVisibility(View.GONE);
        DisposUtil.close(timerDispo);
        Map<String, String> buyerMap = new HashMap<>();
        Map<String, String> sellerMap = new HashMap<>();
        buyerMap.put("1", FabiOrderStatusEnum.待付款.getTitle());
        buyerMap.put("2", FabiOrderStatusEnum.等待对方放币.getTitle());
        buyerMap.put("3", FabiOrderStatusEnum.已完成.getTitle());
        buyerMap.put("4", FabiOrderStatusEnum.申诉中.getTitle());
        buyerMap.put("5", FabiOrderStatusEnum.已取消.getTitle());
        sellerMap.put("1", FabiOrderStatusEnum.待付款.getTitle());
        sellerMap.put("2", FabiOrderStatusEnum.等待对方付款.getTitle());
        sellerMap.put("3", FabiOrderStatusEnum.已完成.getTitle());
        sellerMap.put("4", FabiOrderStatusEnum.申诉中.getTitle());
        sellerMap.put("5", FabiOrderStatusEnum.已取消.getTitle());


        String title = String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity4_h), data.getOop_name(), isBuyer ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle(), CoinUtil.keepUSDT(data.getTotalNum()));

        SpannableStringBuilder ssbTitle = new SpannableStringBuilder(title);
        int start = title.indexOf(" ");
        if (LanguageUtil.isSimpleChinese()) {
            ssbTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)), start, start + 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        tvTitleOrder.setText(ssbTitle);

        tvOrderNum.setText(data.getDealEntrustNo());
        tvStatus.setText(isBuyer ? buyerMap.get(data.getStatus()) : sellerMap.get(data.getStatus()));
        tvTradeType.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordActivity2_h), isBuyer ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        tvPrice.setText(String.format("%s CNY", CoinUtil.keepRMB(data.getPrice())));
        tvNum.setText(String.format("%s USDT", CoinUtil.keepUSDT(data.getTotalNum())));
        tvAllMoney.setText(String.format("%s CNY", CoinUtil.keepRMB(data.getTotalPrice())));
        tvRemark.setText(data.getNotes());
        if (LanguageUtil.getAppLocale(App.INSTANCE) == Locale.SIMPLIFIED_CHINESE) {
            ImageUtil.setImage(R.mipmap.fabi_icon_call, ivCall);
        } else {
            ImageUtil.setImage(R.mipmap.fabi_icon_call_en, ivCall);
        }
        ClickUtil.click(ivCall, () -> {
            IntentUtil.call(this, data.getOop_mobile());
        });
        if (data.getStockUserPayWays() != null) {
            payTypeDispo = Flowable.fromIterable(data.getStockUserPayWays())
                    .subscribe(payType -> {
                        switch (payType.getType()) {
                            case "wx":
                                llWeChat.setVisibility(View.VISIBLE);
                                tvWeChatAccount.setText(payType.getNumber());
                                ClickUtil.click(ivWechat, () -> {
                                    showQR(payType);
                                });
                                break;
                            case "alipay":
                                llAlipay.setVisibility(View.VISIBLE);
                                tvAlipayAccount.setText(payType.getNumber());
                                ClickUtil.click(ivAlipay, () -> {
                                    showQR(payType);
                                });
                                break;
                            case "backcard":
                                llBank.setVisibility(View.VISIBLE);
                                tvBank.setText(payType.getBank());
                                tvBankAccount.setText(payType.getNumber());
                                tvBankBranch.setText(payType.getBranch());
                                ClickUtil.click(tvBankAccount, () -> {
                                    CopyUtil.copy(payType.getNumber());
                                });
                                break;
                        }

                    });
        }
        llSellerWaitPay.setVisibility(View.GONE);
        llBuyerWaitPay.setVisibility(View.GONE);
        llBuyerWaitCoin.setVisibility(View.GONE);
        llSellerWaitCoin.setVisibility(View.GONE);
        llAppealing.setVisibility(View.GONE);
        llCancel.setVisibility(View.GONE);
        llComplete.setVisibility(View.GONE);
        DisposUtil.close(timerDispo);

        if (isBuyer) {//买家页面
            switch (data.getStatus()) {
                case "1"://未支付
                    buyerUnPay();
                    break;
                case "2"://等待放币
                    buyerWaitCoin();
                    break;
                case "4"://卖家申诉中
                    buyerAndSellerAppeal();
                    break;
                case "5"://订单取消
                    orderCancel();
                    break;
                case "3"://订单完成
                    orderComplete();
                    break;

            }
        } else {//卖家页面

            switch (data.getStatus()) {
                case "1"://待付款
                    sellerUnPay();
                    break;
                case "2"://待放币
                    sellerWaitCoin();
                    break;
                case "4"://卖家申诉中
                    buyerAndSellerAppeal();
                    break;
                case "5"://订单取消
                    orderCancel();
                    break;
                case "3"://订单完成
                    orderComplete();
                    break;

            }
        }
    }

    /**
     * 卖家等待放币
     */
    private void sellerWaitCoin() {

        llSellerWaitCoin.setVisibility(View.VISIBLE);
        tvSellerWaitCoinFirst.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity6_h), data.getRefer()));
        String time = TimeFormatUtil.parseTime(data.getQr_time());
        SpannableStringBuilder ssbTitle = new SpannableStringBuilder(
                String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity7_h),
                        time));
        if (LanguageUtil.isSimpleChinese()) {

            ssbTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)),
                    23,
                    23 + time.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        tvSellerWaitCoinSecond.setText(ssbTitle);
        timerDispo = Flowable.intervalRange(1, data.getQr_time(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getQr_time() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    String timeIn = TimeFormatUtil.parseTime(i);
                    SpannableStringBuilder ssbTitleIn = new SpannableStringBuilder(
                            String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity7_h),
                                    timeIn));
                    if (LanguageUtil.isSimpleChinese()) {

                        ssbTitleIn.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)),
                                23,
                                23 + timeIn.length(),
                                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    }
                    tvSellerWaitCoinSecond.setText(ssbTitleIn);
                });
        ClickUtil.click(tvSellerWaitCoinCancel, () -> {//申诉
            showAppeal();
        });
        ClickUtil.click(btSellerWaitCoinSure, () -> {//放币
            showPwdBottom();
        });
        refreshTimerOrder();
    }

    /**
     * 显示申诉弹窗
     */
    private void showAppeal() {
        //使用自定义的ArrayAdapter
        mAdapter = new SpinnerTextColorAdapter(this, stringArray);
        if (tipAppealDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view = View.inflate(this, R.layout.fabi_dialog_appeal, null);

            builder.setView(view);
            builder.setCancelable(true);
            EditText etReason = view.findViewById(R.id.et_reason);
            Spinner spinner = view.findViewById(R.id.spinner);
            ClickUtil.click(view.findViewById(R.id.tv_cancel), () -> tipAppealDialog.dismiss());
            ClickUtil.click(view.findViewById(R.id.tv_apply), () -> {
                tipAppealDialog.dismiss();
                String type = spinner.getSelectedItem().toString();
                String reason = etReason.getText().toString();
                mPresenter.allegeOrder(orderNum, data.getRefer(), data.getOop_account(), type, reason);

            });
            spinner.setAdapter(mAdapter);
            tipAppealDialog = builder.create();
        }

        tipAppealDialog.show();

    }

    /**
     * 显示交易密码底部弹窗
     */
    private void showPwdBottom() {

        if (codeDialog == null) {
            codeDialog = TipFabiUtil.getPay(this, str -> {
                codeDialog.dismiss();
                mPresenter.letGo(orderNum, str[0]);
            });
        }
        codeDialog.show();
    }

    /**
     * 卖家未支付
     */
    private void sellerUnPay() {

        llSellerWaitPay.setVisibility(View.VISIBLE);
        String time = TimeFormatUtil.parseTime(data.getDown_time());
        SpannableStringBuilder ssbTitle = new SpannableStringBuilder(
                String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity8_h),
                        data.getOop_name(), time, data.getRefer()));
        if (LanguageUtil.isSimpleChinese()) {

            ssbTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)),
                    9 + data.getOop_name().length(),
                    9 + data.getOop_name().length() + time.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        tvSellerWaitPayFirst.setText(ssbTitle);
        timerDispo = Flowable.intervalRange(1, data.getDown_time(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getDown_time() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    String timeIn = TimeFormatUtil.parseTime(i);
                    SpannableStringBuilder ssbTitleIn = new SpannableStringBuilder(
                            String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity8_h),
                                    data.getOop_name(), timeIn, data.getRefer()));
                    if (LanguageUtil.isSimpleChinese()) {
                        ssbTitleIn.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)),
                                9 + data.getOop_name().length(),
                                9 + data.getOop_name().length() + timeIn.length(),
                                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    }
                    tvSellerWaitPayFirst.setText(ssbTitleIn);
                });
        ClickUtil.click(btSellerWaitPaySure, () -> {
            showCancelTip();
        });
        refreshTimerOrder();
    }


    /**
     * 订单完成
     */
    private void orderComplete() {
        tvComplete.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity9_h), data.getRefer()));
        llComplete.setVisibility(View.VISIBLE);
        DisposUtil.close(detailDispo);
    }

    /**
     * 订单取消
     */
    private void orderCancel() {

        llCancel.setVisibility(View.VISIBLE);
        DisposUtil.close(detailDispo);

    }

    private void buyerAndSellerAppeal() {

        llAppealing.setVisibility(View.VISIBLE);
        tvAppealing.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity10_h), data.getCommand(), data.getRefer()));
    }

    /**
     * 买家未支付
     */
    private void buyerUnPay() {
        llBuyerWaitPay.setVisibility(View.VISIBLE);

        String time = TimeFormatUtil.parseTime(data.getDown_time());
        tvBuyerFirst.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity11_h), time, data.getOop_name(), data.getRefer()));
        SpannableStringBuilder ssb = new SpannableStringBuilder(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity12_h));
        if (LanguageUtil.isSimpleChinese()) {
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)), 9, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        tvBuyerSecond.setText(ssb);
        timerDispo = Flowable.intervalRange(1, data.getDown_time(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getDown_time() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    tvBuyerFirst.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity11_h), TimeFormatUtil.parseTime(i), data.getOop_name(), data.getRefer()));

                });
        ClickUtil.click(btBuyerSure, () -> {//标记付款
            showPayTip();
        });
        ClickUtil.click(tvBuyerCancel, () -> {//取消订单
            showCancelTip();
        });
        refreshTimerOrder();
    }

    /**
     * 买家等待放币
     */
    private void buyerWaitCoin() {
        llBuyerWaitCoin.setVisibility(View.VISIBLE);
        tvBuyerWaitCoinFirst.setText(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity13_h), data.getRefer()));
        String time = TimeFormatUtil.parseTime(data.getQr_time());
        SpannableStringBuilder ssbTitle = new SpannableStringBuilder(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity14_h), time));
        if (LanguageUtil.isSimpleChinese()) {
            ssbTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)), 5, time.length() + 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        tvBuyerWaitCoinSecond.setText(ssbTitle);
        timerDispo = Flowable.intervalRange(1, data.getQr_time(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getQr_time() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    String timeIn = TimeFormatUtil.parseTime(i);
                    SpannableStringBuilder ssbTitleIn = new SpannableStringBuilder(String.format(App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity14_h), timeIn));
                    if (LanguageUtil.isSimpleChinese()) {
                        ssbTitleIn.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_706)), 5, timeIn.length() + 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    }
                    tvBuyerWaitCoinSecond.setText(ssbTitleIn);
                });
        refreshTimerOrder();

    }

    /**
     * 支付完成提示弹窗
     */
    private void showPayTip() {
        if (payTipDialog == null) {
            payTipDialog = TipUtil.getSureCancelTip(this, App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity15_h), App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity16_h), () -> mPresenter.markPay(orderNum));
        }
        payTipDialog.show();
    }

    /**
     * 显示二维码弹窗
     */
    private void showQR(OrderDetailBean.StockUserPayWaysBean dataItem) {
        TipFabiUtil.showQR(this, dataItem.getImg());
    }

    /**
     * 显示撤单提示
     */
    private void showCancelTip() {
        if (tipCancleDialog == null) {
            tipCancleDialog = TipUtil.getTip(this, App.INSTANCE.getString(R.string.fabi_orderRecordDetailActivity17_h), () -> {
                mPresenter.cancelOrder(orderNum);

            });

        }
        tipCancleDialog.show();
    }


    /**
     * 定时刷新订单信息
     */
    private void refreshTimerOrder() {
        if (detailDispo == null || detailDispo.isDisposed()) {
            detailDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                    .subscribe(aLong -> {
                        mPresenter.getOrderInfo(orderNum, false);
                    });
        }
    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(timerDispo);

        super.onDestroy();
    }
}
